package com.mdms.filters;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.mdms.jsf.managedbeans.user.UserMBean;
import com.mdms.utils.FacesUtils;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		FacesContext ctx = FacesContext.getCurrentInstance();
		if(ctx==null){
			FacesContextBuilder builder = new FacesContextBuilder();
			ctx = builder.getFacesContext(arg0, arg1);
		}
		UserMBean bean = (UserMBean)FacesUtils.getManagedBeanValue("userMBean");
		if(bean==null || !bean.isAlreadyLogin()){
			 String contextPath = ((HttpServletRequest)arg0).getContextPath();
	            ((HttpServletResponse)arg1).sendRedirect(contextPath + "/login.xhtml");
	
		}
		ctx.release();
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
		
	}

}
